package com.xvyy.tingshu.order.adapter.impl;

import com.xvyy.tingshu.album.client.AlbumInfoFeignClient;
import com.xvyy.tingshu.common.constant.SystemConstant;
import com.xvyy.tingshu.common.execption.TsException;
import com.xvyy.tingshu.common.result.Result;
import com.xvyy.tingshu.model.album.AlbumInfo;
import com.xvyy.tingshu.order.adapter.OrderDealTypeAdapter;
import com.xvyy.tingshu.order.mapper.OrderInfoMapper;
import com.xvyy.tingshu.user.client.UserInfoFeignClient;
import com.xvyy.tingshu.vo.order.OrderDerateVo;
import com.xvyy.tingshu.vo.order.OrderDetailVo;
import com.xvyy.tingshu.vo.order.OrderInfoVo;
import com.xvyy.tingshu.vo.order.TradeVo;
import com.xvyy.tingshu.vo.user.UserInfoVo;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

/**
 * ClassName: OrderDealTypeByAlbum
 * Package: com.xvyy.tingshu.order.adapter.impl
 *
 * @Description:
 * @Author: xvyy
 * @Create: 2025/2/16 - 0:13
 * @Version: v1.0
 */
@Component
@Slf4j
public class OrderDealTypeByAlbum implements OrderDealTypeAdapter {

    @Autowired
    private UserInfoFeignClient userInfoFeignClient;
    @Autowired
    private AlbumInfoFeignClient albumInfoFeignClient;
    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Override
    public Boolean supportOrderDealType(String dealType) {
        return dealType.equals(SystemConstant.ORDER_ITEM_TYPE_ALBUM); // 1001 表示专辑
    }

    @Override
    public OrderInfoVo adapterOrderDealType(TradeVo tradeVo, Long userId, String itemType) {
        OrderInfoVo orderInfoVoResult = new OrderInfoVo();
        // 1. 远程调用user微服务，判断是否买过该专辑
        Long albumId = tradeVo.getItemId();
        Result<Boolean> userPaidAlbumResult = userInfoFeignClient.getUserPaidAlbum(userId, albumId);
        Boolean userPaidAlbumData = userPaidAlbumResult.getData();
        Assert.notNull(userPaidAlbumData, "远程调用user微服务，判断是否买过该专辑失败");
        if (userPaidAlbumData) {
            log.error("用户{}已经购买过{}专辑，无需重复购买", userId, albumId);
            throw new TsException(201, "该付款项目已经购买过，请勿重复购买");
        }
        // 2. 判断是否在支付中
        int count = orderInfoMapper.checkAlbumAndVipTypeItemPadding(itemType, userId, albumId);
        if (count != 0) {
            log.error("该付款项专辑：{}，处于购买中，请勿继续购买该专辑", albumId);
            orderInfoVoResult.setExitItemIdList(Lists.newArrayList(albumId));
            return orderInfoVoResult;
        }
        // 3. 给OrderInfoVo赋值
        // 3.1 订单号 RandomStringUtils.random(15,true,false); : 生成15位随机字符串，字母和数字混合
        String tradeNo = RandomStringUtils.random(15, true, false);
        orderInfoVoResult.setTradeNo(tradeNo);
        // 3.2 支付方式
        orderInfoVoResult.setPayWay("");
        // 3.3 交易类型
        orderInfoVoResult.setItemType(itemType);
        // 3.4 原始金额 远程调用album微服务，在专辑信息中获取原始金额
        Result<AlbumInfo> albumInfoResult = albumInfoFeignClient.getAlbumInfo(albumId);
        AlbumInfo albumInfoData = albumInfoResult.getData();
        Assert.notNull(albumInfoData, "远程调用album微服务，获取专辑信息失败");
        BigDecimal originalAmount = albumInfoData.getPrice();
        orderInfoVoResult.setOriginalAmount(originalAmount.setScale(2, RoundingMode.HALF_UP));// 原始金额，保留两位小数，四舍五入
        // 3.5 减免金额
        // 3.5.1 远程调用user微服务，在用户付费专辑列表中获取减免金额
        Result<UserInfoVo> userInfoVoResult = userInfoFeignClient.getUserInfoVo(userId);
        UserInfoVo userInfoVoData = userInfoVoResult.getData();
        Assert.notNull(userInfoVoData, "远程调用user微服务，获取用户信息失败");
        Integer isVip = userInfoVoData.getIsVip();
        BigDecimal disCount = null;
        // 3.5.2 判断用户是否为vip会员
        if (isVip.equals("1")) {
            // 用户是vip会员
            disCount = albumInfoData.getVipDiscount();
        } else {
            // 用户不是vip会员
            disCount = albumInfoData.getDiscount();
        }
        if (disCount.intValue() == -1) {
            // 没有折扣，不打折
            disCount = new BigDecimal("10.00");
        }
        // 3.5.3 减免金额计算 = 原价格 - (原价格 * 折扣 / 10) 保留两位小数，四舍五入
        BigDecimal derateAmount = originalAmount.subtract(originalAmount.multiply(disCount).divide(new BigDecimal("10.00")));
        orderInfoVoResult.setDerateAmount(derateAmount.setScale(2, RoundingMode.HALF_UP));
        // 3.6 实付金额 = 原价格 - 减免金额 保留两位小数，四舍五入
        BigDecimal orderAmount = originalAmount.subtract(derateAmount.setScale(2, RoundingMode.HALF_UP));
        orderInfoVoResult.setOrderAmount(orderAmount.setScale(2, RoundingMode.HALF_UP));
        // 3.7 订单详情列表
        List<OrderDetailVo> orderDetailVoList = new ArrayList<>();
        OrderDetailVo orderDetailVo = new OrderDetailVo();
        orderDetailVo.setItemId(albumId);// 专辑id
        orderDetailVo.setItemName(albumInfoData.getAlbumTitle());// 专辑名称
        orderDetailVo.setItemUrl(albumInfoData.getCoverUrl());// 封面图片地址
        orderDetailVo.setItemPrice(originalAmount);// 原价
        orderDetailVoList.add(orderDetailVo);
        orderInfoVoResult.setOrderDetailVoList(Lists.newArrayList(orderDetailVoList));
        // 3.8 订单减免列表
        List<OrderDerateVo> orderDerateVoList = new ArrayList<>();
        OrderDerateVo orderDerateVo = new OrderDerateVo();
        orderDerateVo.setDerateType("专辑折扣");// 折扣类型
        orderDerateVo.setDerateAmount(derateAmount.setScale(2, RoundingMode.HALF_UP));// 折扣：10.00，
        orderDerateVo.setRemarks("订单减免类型专辑折扣减免");// 备注信息
        orderDerateVoList.add(orderDerateVo);
        orderInfoVoResult.setOrderDerateVoList(Lists.newArrayList(orderDerateVoList));
        // 4. 返回结果
        return orderInfoVoResult;
    }
}
